package externalSort.Tournament;

public class bufferSimulator {
    private BufferState state;
    public int[] data;  // CRITICAL SECTION PROBLEM!
    private int readIndex;  // 读取位置
    private int writeIndex; // 写入位置
    private int count;      // 当前元素数量
//
//    public int getReadIndex() {
//        return readIndex;
//    }
//
//    public void setReadIndex(int readIndex) {
//        this.readIndex = readIndex;
//    }
//
//    public int getWriteIndex() {
//        return writeIndex;
//    }
//
//    public void setWriteIndex(int writeIndex) {
//        this.writeIndex = writeIndex;
//    }
//
//    public int getCount() {
//        return count;
//    }
//
//    public ReadBufferState getState() {
//        return state;
//    }
//
//    public void setState(ReadBufferState state) {
//        this.state = state;
//    }

    public BufferState getState() {
        return state;
    }

    public void setState(BufferState state) {
        this.state = state;
    }

    /**
     * 向循环队列添加元素
     * @param num 要添加的数字
     * @return 添加成功返回true，队列已满返回false
     */
    public boolean add(int num) {
        if (isFull()) {
            System.out.println("[externalSort.bufferSimulator.add] 队列已满，无法添加");
            return false;
        }

        this.data[writeIndex] = num;
        writeIndex = (writeIndex + 1) % capacity;
        count++;
        return true;
    }

    /**
     * 从循环队列取出元素
     * @return 队列头的元素，队列为空返回Integer.MAX_VALUE
     */
    public int poll() {
        if (isEmpty()) {
            System.out.println("[externalSort.bufferSimulator.poll] 队列为空，无法取出");
            return Integer.MAX_VALUE;
        }

        int value = this.data[readIndex];
        readIndex = (readIndex + 1) % capacity;
        count--;
        return value;
    }

    /**
     * 查看队列头元素但不取出
     * @return 队列头元素，队列为空返回Integer.MAX_VALUE
     */
    public int peek() {
        if (isEmpty()) {
            return Integer.MAX_VALUE;
        }
        return this.data[readIndex];
    }

    public int back(){
        if (isEmpty()) {
            return Integer.MAX_VALUE;
        }
        return this.data[(writeIndex+capacity-1)%capacity];
    }

    public boolean isFull() {
        return this.count == this.capacity;
    }

    public boolean isEmpty() {
        return this.count == 0;
    }

    /**
     * 清空队列
     */
    public void clear() {
        readIndex = 0;
        writeIndex = 0;
        count = 0;
    }

    /**
     * 获取队列中元素数量
     */
    public int size() {
        return count;
    }

    public int capacity;

    public bufferSimulator(int capacity) {
        this.capacity = capacity;
        data = new int[capacity];
        this.readIndex = 0;
        this.writeIndex = 0;
        this.count = 0;
    }
}